package com.bzg.spring.component;

import com.bzg.spring.annotation.Aop;
import com.bzg.spring.annotation.MyComponent;
import com.bzg.spring.application.MyBeanPostProcessor;
import org.springframework.beans.BeansException;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@MyComponent
public class CustomBeanPostProcessor implements MyBeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		System.out.println(beanName + " 前置初始化");
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		System.out.println(beanName + " 后置初始化");
		Aop annotation = bean.getClass().getAnnotation(Aop.class); // 做代理，这里采用jdk代理
		if (annotation != null) {  // 此处没考虑循环依赖的代理处理，就采用普通后置初始化处理
			Class<?>[] interfaces = bean.getClass().getInterfaces();
			Object o = Proxy.newProxyInstance(CustomBeanPostProcessor.class.getClassLoader(), interfaces, new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					System.out.println(beanName + " 代理");
					return method.invoke(bean, args);
				}
			});
			return o;
		}
		return bean;
	}
}
